package com.zhixiang.xaec.action.system;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.zhixiang.core.util.AppUtil;
import com.zhixiang.core.util.BackupUtils;
import com.zhixiang.core.util.FileUtils;
import com.zhixiang.core.web.action.BaseAction;

@Controller
@Scope("prototype")
public class BackupAction extends BaseAction
{

    private static final long serialVersionUID = 8217039609902806672L;

    private File file ; //具体上传文件的 引用 , 指向临时目录中的临时文件  
    private String fileFileName ;  // 上传文件的名字 ,FileName 固定的写法  
    private String fileContentType ; //上传文件的类型， ContentType 固定的写法  
    
    public void bakupAndDowload()
    {
        try
        {
            getResponse().setCharacterEncoding("UTF-8");
            getResponse().setContentType("application/x-msdownload; ");
            String fileName = generationBackupFileName();
            getResponse().addHeader("Content-Disposition",
                "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            OutputStream outputStream = getResponse().getOutputStream();
            BackupUtils.backup(outputStream);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void download()
    {
        String filePath = getRequest().getParameter("filePath");
        if (!FileUtils.isExist(filePath))
        {
            filePath = getTmpDir() + "/" + generationBackupFileName();
        }

        try
        {
            File file = new File(filePath);
            String fileName = file.getName();
            FileInputStream filein = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(filein, "utf-8");
            // 设置输出流编码为utf-8。这里必须是utf-8，否则从流中读入的是乱码
            String inStr;
            StringBuffer sb = new StringBuffer("");
            String outStr;
            // 组合控制台输出信息字符串
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            while ((inStr = bufferedReader.readLine()) != null)
            {
                sb.append(inStr + "\r\n");
            }
            outStr = sb.toString();

            getResponse().setCharacterEncoding("UTF-8");
            getResponse().setContentType("application/x-msdownload; ");
            getResponse().addHeader("Content-Disposition",
                "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            // response.setHeader("Content-Length",String.valueOf(StringUtils.length(outStr)));

            OutputStream out = getResponse().getOutputStream();
            OutputStreamWriter writer = new OutputStreamWriter(out, "utf-8");
            writer.write(outStr);
            filein.close();
            inputStreamReader.close();
            bufferedReader.close();
            out.close();
            writer.close();

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public String backup()
    {
        String backupPath = getRequest().getParameter("backupPath");
        if (StringUtils.isEmpty(backupPath))
        {
            backupPath = getTmpDir() + "/" + generationBackupFileName();
        }

        if (FileUtils.isExist(backupPath))
        {
            setMsg("备份文件已经存在！");
            setSuccess(false);
        }
        else
        {
            try
            {
                BackupUtils.backup(backupPath);
                setMsg("备份成功。请到服务器" + backupPath + "查看备份文件！");
            }
            catch (Exception e)
            {
                e.printStackTrace();
                setMsg("备份失败，请检查文件备份路径是否正确或者是否有目录权限！");
                setSuccess(false);
            }
        }

        return SUCCESS;
    }

    public String restore()
    {
        try
        {
            if(getFile()!=null){
                InputStream input = new FileInputStream(getFile());
                BackupUtils.restore(input);
                setMsg("还原成功，请重启PTMS服务，使还原的数据生效！");
            }else{
                setMsg("还原失败，请重新选择还原文件！");
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            setMsg("还原失败，请重新选择还原文件！");
        }
        return SUCCESS;
    }

    private String generationBackupFileName()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_hhmmss_SSS");
        String currentTime = sdf.format(new Date());
        String fileName = "ptmsdb_" + currentTime + ".bak";
        return fileName;
    }

    private String getTmpDir()
    {
        String tmpDir = AppUtil.getSysConfig().get("uploadDir") + "/DataBaseBak";
        File file = new File(tmpDir);
        if (!file.exists())
        {
            file.mkdir();
        }
        return tmpDir;
    }

    public File getFile()
    {
        return file;
    }

    public void setFile(File file)
    {
        this.file = file;
    }

    public String getFileFileName()
    {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName)
    {
        this.fileFileName = fileFileName;
    }

    public String getFileContentType()
    {
        return fileContentType;
    }

    public void setFileContentType(String fileContentType)
    {
        this.fileContentType = fileContentType;
    }

    
}
